<?php

namespace App\Http\Controllers\Passenger\V2\Order;

use App\Http\Controllers\Controller;
use App\Models\DriverFinancial;
use App\Models\OrderFlow;
use App\Models\Orders;
use App\Models\PayOrder;
use App\Models\RechargeRecord;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade;

class PayNotifyController extends Controller
{


    /**
     * 小程序支付回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function wxminiPredict()
    {

        $payment = Facade::payment();

        $response = $payment->handlePaidNotify(function ($message, $fail) {

            // 根据返回的订单号查询订单数据
            $out_trade_no = substr($message['out_trade_no'], 0, 1);
            $out_trade_nos = $message['out_trade_no'];
            $total_fee = $message['total_fee'] / 100;
            if ($out_trade_no == 'B') {
                if ($message['result_code'] === 'SUCCESS') {
                    DB::transaction(function () use ($out_trade_no, $out_trade_nos, $total_fee) {
                        $recharge_record = RechargeRecord::query()->where('status', 0)->where('order_sn', $out_trade_nos)->orderByDesc('created_at')->first();
                        if (!$recharge_record) return true;
                        User::query()->where('id', $recharge_record->user_id)->update([
                            'balance' => DB::raw('balance +' . $total_fee)
                        ]);
                        $recharge_record->status = 1; //已支付
                        $recharge_record->save();
                    });
                    return true;
                }
                return true;

            } else {
                $pay_order_info = PayOrder::query()->firstWhere('sn', $message['out_trade_no']);
                if (!$pay_order_info)
                    $fail('Pay Order not exist.');

                if ($pay_order_info->status == 1)
                    return true;

                $order_info = Orders::query()->find($pay_order_info->order_id);
                if (!$order_info)
                    $fail('Order not exist.');

//            if ($pay_order_info->status  != 0) {
//                return true;
//            }

                // 支付成功后的业务逻辑
                if ($message['result_code'] === 'SUCCESS') {

                    DB::beginTransaction();
                    $pay_order_info->status = 1;
                    $pay_order_info->pay_type = 1; //微信支付
                    $pay_order_info->pay_sn = $message['transaction_id'];
                    $pay_order_info->success_time = strtotime($message['time_end']);
                    $pay_order_info->pay_data = json_encode($message);

                    if (!$pay_order_info->save())
                        $fail('Pay Order Error');

                    if ($pay_order_info->type == 1) { //预支付费用
                        $order_info->status = '1';
                        $order_info->is_pay_predict = 1;
                        $order_info->real_price = $message['total_fee'] / 100;
                    }

                    if ($pay_order_info->type == 2) { //支付取消责任费
                        $order_info->cancel_status = 0;
                    }

                    if ($pay_order_info->type == 3) { //服务结束补款
                        $order_info->status = '5';
                        $order_info->real_price = $order_info->real_price + ($message['total_fee'] / 100);
                    }

                    if ($order_info->save() === false) {
                        DB::rollBack();
                        $fail('Order Error');
                    }
                    //todo 添加流水
                    $order_flow = new OrderFlow();
                    $order_flow->user_id = $order_info->user_id;
                    $order_flow->order_id = $order_info->id;
                    $order_flow->order_sn = $order_info->order_sn;
                    $order_flow->pay_sn = $message['transaction_id'];
                    $order_flow->price = $message['total_fee'] / 100;
                    if ($order_flow->save() === false) {
                        DB::rollBack();
                        $fail('Order Flow Error');
                    }

                    //todo 呼叫车辆
                    DB::commit();
                }

                return true;
            }
        });

        return $response;
    }
}
